Exercise: Adding Type Hints
Add type hints to the following functions. Make sure that no red squiggles appear in your IDE with your type checker set to "strict".
Make sure that you have installed pylance or similar to get type hints in your IDE.
def add_book(collection, title, author):
collection.append({"title": title, "author": author})
def display_books(collection):
for book in collection:
print(f"Title: {book['title']}, Author: {book['author']}")
def find_book_by_title(collection, title):
for book in collection:
if book['title'] == title:
return book
return None
def filter_even_numbers(numbers):
return [num for num in numbers if num % 2 == 0]
def main():
my_books = []
add_book(my_books, "1984", "George Orwell")
add_book(my_books, "To Kill a Mockingbird", "Harper Lee")
display_books(my_books)
if __name__ == "__main__":
main()
collection.append({"title": title, "author": author})
def display_books(collection):
for book in collection:
print(f"Title: {book['title']}, Author: {book['author']}")
def find_book_by_title(collection, title):
for book in collection:
if book['title'] == title:
return book
return None
def filter_even_numbers(numbers):
return [num for num in numbers if num % 2 == 0]
def main():
my_books = []
add_book(my_books, "1984", "George Orwell")
add_book(my_books, "To Kill a Mockingbird", "Harper Lee")
display_books(my_books)
if __name__ == "__main__":
main()
Compatible Python Versions: 3.9+
Hi, I have Pylance installed and am working in a virtual environment using Python 3.10.9 in VS Code on a Windows 10 machine. I do not see any squiggles. I understand the exercise, but am wondering if there is a versioning/set up that I'm missing.
Update: I added "python.analysis.typeCheckingMode": "basic" to "settings.json" and that produced some squiggles, but not entirely sure the behavior is as expected.
Thanks!
Hi! The typeCheckingMode is what you want to change! Usually, we try to have the "strict" mode. Unfortunately, I do not have a great resource on this that I can share.
No worries. Thanks for letting me know. I didn't think Arjan was so `strict`! ;-)
No worries! It is a blessing and a curse to have a certain strictness in programming ;)
I got all things right in the first attempt, but then realized after checking the solution that the expectation was to give type-hints down to the basic datatype in Python. E.g., it was not enough to just call something as list, but it was expected to clearly specify: list[dict[str, str]]
Nice job! The exercises try to adhere to a strict type evaluation.
It looks like the solution for the "find_book_by_title" function is missing in Github repo.
Thanks for acknowledging this! It should be fixed now!
Is the answer somehwere to check?
Hi Chris! Everything is stored in the GitHub repository. If you do not want to clone that repo, you can get the whole repo through this part of the course